package com.yuncheng.spcyApi.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.entity.SpcyRsCity;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.ISpcyRsCityService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.spcyApi.vo.common.HttpCityVo;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import com.yuncheng.spcyApi.vo.common.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * @author hua
 */
@Api(tags = "省份城市库管理")
@RestController
@RequestMapping("/api/spzx-spcy/RsCity")
public class SpcyRsCityController {

    @Resource
    @Lazy
    private ISpcyRsCityService spcyRsCityService;

    /**
     * 同步省份城市
     * @return
     * @throws Exception
     */
    @GetMapping(value = "syncCity")
    public HttpResult syncCity() throws Exception {

        List<SpcyRsCity> list = CityUtils.getAllProvinceCityArea();
        if (CollectionUtil.isNotEmpty(list)) {
            spcyRsCityService.saveBatch(list);
        }

        return HttpResult.ok();
    }

    @ApiOperation(value = "查询所有省份列表")
    @GetMapping(value = "queryProviceList")
    public HttpResult queryProviceList(@RequestParam(value = "gjz",defaultValue = "") String gjz) {

        LambdaQueryWrapper<SpcyRsCity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(gjz), SpcyRsCity::getProvince, gjz);
        queryWrapper.isNotNull(SpcyRsCity::getProvince);
        queryWrapper.orderByAsc(SpcyRsCity::getForder);
        List<SpcyRsCity> list = spcyRsCityService.list(queryWrapper);

        List<HttpCityVo> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            HttpCityVo cityVo = null;
            for (int i = 0; i < list.size(); i++) {
                cityVo = new HttpCityVo();
                cityVo.setCode(list.get(i).getId());
                cityVo.setName(list.get(i).getProvince());
                cityVo.setCity(list.get(i).getProvince());
                cityVo.setArea(list.get(i).getProvince());
                resultList.add(cityVo);
            }
        }

        return HttpResult.ok(resultList);
    }

    @ApiOperation(value = "查询所有城市列表")
    @GetMapping(value = "queryCityList")
    public HttpResult queryCityList(@RequestParam(value = "gjz",defaultValue = "") String gjz,
                                    @RequestParam(value = "code",defaultValue = "") String code) {

        LambdaQueryWrapper<SpcyRsCity> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isBlank(code)) {
            queryWrapper.isNotNull(SpcyRsCity::getCity);
            queryWrapper.like(StringUtils.isNotBlank(gjz), SpcyRsCity::getProvincecity, gjz);
        }else {

            queryWrapper.eq(SpcyRsCity::getProvinceid, code);
            queryWrapper.like(StringUtils.isNotBlank(gjz), SpcyRsCity::getCity, gjz);
        }

        queryWrapper.orderByAsc(SpcyRsCity::getForder);
        List<SpcyRsCity> list = spcyRsCityService.list(queryWrapper);

        List<HttpCityVo> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            HttpCityVo cityVo = null;
            for (int i = 0; i < list.size(); i++) {
                cityVo = new HttpCityVo();
                cityVo.setCode(list.get(i).getId());
                cityVo.setName(list.get(i).getCity());
                cityVo.setCity(list.get(i).getProvincecity());
                cityVo.setArea(list.get(i).getProvincecity());
                resultList.add(cityVo);
            }
        }

        return HttpResult.ok(resultList);
    }

    @ApiOperation(value = "查询所有区域列表")
    @GetMapping(value = "queryAreaList")
    public HttpResult queryAreaList(@RequestParam(value = "gjz",defaultValue = "") String gjz,
                                    @RequestParam(value = "code",defaultValue = "") String code) {

        LambdaQueryWrapper<SpcyRsCity> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isBlank(code)) {
            queryWrapper.isNotNull(SpcyRsCity::getArea);
            queryWrapper.like(StringUtils.isNotBlank(gjz), SpcyRsCity::getProvincecityarea, gjz);
        }else {
            queryWrapper.eq(SpcyRsCity::getCityid, code);
            queryWrapper.like(StringUtils.isNotBlank(gjz), SpcyRsCity::getArea, gjz);
        }

        queryWrapper.orderByAsc(SpcyRsCity::getForder);
        List<SpcyRsCity> list = spcyRsCityService.list(queryWrapper);

        List<HttpCityVo> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            HttpCityVo cityVo = null;
            for (int i = 0; i < list.size(); i++) {
                cityVo = new HttpCityVo();
                cityVo.setCode(list.get(i).getId());
                cityVo.setName(list.get(i).getArea());
                cityVo.setCity(list.get(i).getProvincecity());
                cityVo.setArea(list.get(i).getProvincecityarea());
                resultList.add(cityVo);
            }
        }

        return HttpResult.ok(resultList);
    }

    @ApiOperation(value = "查询搜索列表")
    @GetMapping(value = "querySearchList")
    public HttpResult querySearchList(@RequestParam(value = "gjz",defaultValue = "") String gjz) {

        LambdaQueryWrapper<SpcyRsCity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNotNull(SpcyRsCity::getArea);
        queryWrapper.like(StringUtils.isNotBlank(gjz), SpcyRsCity::getProvincecityarea, gjz);


        queryWrapper.orderByAsc(SpcyRsCity::getForder);
        List<SpcyRsCity> list = spcyRsCityService.list(queryWrapper);

        List<String> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (StringUtils.isNotBlank(list.get(i).getProvincecityarea())) {
                    resultList.add(list.get(i).getProvincecityarea());
                }
            }
        }

        return HttpResult.ok(resultList);
    }


    @ApiOperation(value = "省份城市-分页列表查询")
    @GetMapping(value = "/pageList")
    public HttpResult<?> queryPageList(SpcyRsCity query, String gjz, PageVo pageVo, OrderItemVo orderItemVo) {

        LambdaQueryWrapper<SpcyRsCity> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isBlank(gjz)) {
            queryWrapper.like(StringUtils.isNotBlank(query.getProvince()), SpcyRsCity::getProvince, query.getProvince());
            queryWrapper.like(StringUtils.isNotBlank(query.getCity()), SpcyRsCity::getCity, query.getCity());
            queryWrapper.like(StringUtils.isNotBlank(query.getArea()), SpcyRsCity::getArea, query.getArea());
        }else {
            queryWrapper
                    .and(f -> f.like(SpcyRsCity::getProvince, gjz)
                            .or()
                            .like(SpcyRsCity::getCity, gjz)
                            .or()
                            .like(SpcyRsCity::getArea, gjz)
                    );
        }

        if (StringUtils.isBlank(orderItemVo.getOrderItem())){
            queryWrapper.orderByAsc(SpcyRsCity::getForder);
        }else {
            OrderItemUtils.setOrderItem(queryWrapper, orderItemVo);
        }
        Page<SpcyRsCity> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());
        return HttpResult.ok(spcyRsCityService.page(page, queryWrapper));
    }

    @ApiOperation(value = "省份城市-更新")
    @PutMapping(value = "/edit")
    public HttpResult<?> edit(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException {

        String id = buffer.get("id");
        if (StringUtils.isEmpty(id)){
            throw new BusinessException("参数为空!");
        }

        SpcyRsCity updateBean = spcyRsCityService.getById(id);
        if (updateBean == null){
            throw new BusinessException("没有相匹配数据！");
        }

        /** 1：省份/2: 城市/3：区县 */
        int code = 0;
        String oldName = "";

        // 省份
        if (StringUtils.isBlank(updateBean.getProvinceid()) && StringUtils.isBlank(updateBean.getCityid())){
            code = 1;
            oldName = updateBean.getProvince();
        }

        // 城市
        if (StringUtils.isNotBlank(updateBean.getProvinceid())){
            code = 2;
            oldName = updateBean.getCity();
        }

        // 区县
        if (StringUtils.isNotBlank(updateBean.getCityid())){
            code = 3;
            oldName = updateBean.getArea();
        }

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(updateBean, buffer);

        updateBean.setUpdateBy(GetCurrentUserUtils.getCurrentUserAccount());
        updateBean.setUpdateTime(new Date());

        /** 1：省份/2: 城市/3：区县 */
        if (code == 1){
            // 省份修改
            if (StringUtils.isBlank(updateBean.getProvince())){
                throw new BusinessException("省份不能为空！");
            }

            if (StringUtils.isNotBlank(oldName) && !oldName.equals(updateBean.getProvince())){
                List<SpcyRsCity> cityList = spcyRsCityService.list(new LambdaQueryWrapper<SpcyRsCity>()
                        .eq(SpcyRsCity::getProvinceid, updateBean.getId()));
                if (CollectionUtil.isNotEmpty(cityList)){
                    for (SpcyRsCity city : cityList){
                        city.setProvincecity(updateBean.getProvince() + city.getCity());
                        spcyRsCityService.updateById(city);

                        List<SpcyRsCity> areaList = spcyRsCityService.list(new LambdaQueryWrapper<SpcyRsCity>()
                                .eq(SpcyRsCity::getCityid, city.getId()));
                        if (CollectionUtil.isNotEmpty(areaList)) {
                            for (SpcyRsCity area : areaList) {
                                area.setProvincecity(city.getProvincecity());
                                area.setProvincecityarea(city.getProvincecity() + area.getArea());
                                spcyRsCityService.updateById(area);
                            }
                        }
                    }
                }
            }

        }else if (code == 2){
            // 城市修改
            if (StringUtils.isBlank(updateBean.getCity())){
                throw new BusinessException("城市不能为空！");
            }

            if (StringUtils.isNotBlank(oldName) && !oldName.equals(updateBean.getCity())){
                SpcyRsCity province = spcyRsCityService.getById(updateBean.getProvinceid());
                if (province != null){
                    updateBean.setProvincecity(province.getProvince() + updateBean.getCity());

                    List<SpcyRsCity> areaList = spcyRsCityService.list(new LambdaQueryWrapper<SpcyRsCity>()
                            .eq(SpcyRsCity::getCityid, updateBean.getId()));
                    if (CollectionUtil.isNotEmpty(areaList)) {
                        for (SpcyRsCity area : areaList) {
                            area.setProvincecity(updateBean.getProvincecity());
                            area.setProvincecityarea(updateBean.getProvincecity() + area.getArea());
                            spcyRsCityService.updateById(area);
                        }
                    }
                }
            }

        }else if (code == 3){
            // 区县修改
            if (StringUtils.isBlank(updateBean.getArea())){
                throw new BusinessException("区县不能为空！");
            }

            if (StringUtils.isNotBlank(oldName) && !oldName.equals(updateBean.getArea())){
                SpcyRsCity city = spcyRsCityService.getById(updateBean.getCityid());
                if (city != null){
                    updateBean.setProvincecityarea(city.getProvincecity() + updateBean.getArea());
                }
            }
        }

        spcyRsCityService.updateById(updateBean);

        return HttpResult.ok("保存成功");
    }

    @ApiOperation(value = "省份-添加")
    @PostMapping(value = "addProvice")
    public HttpResult addProvice(@RequestBody SpcyRsCity bean){
        if (StringUtils.isBlank(bean.getProvince())){
            throw new BusinessException("省份为空！");
        }

        bean.setId(GetUuIdUtils.ReplaceUuId());

        bean.setProvinceid("");
        bean.setCityid("");
        bean.setArea("");
        bean.setCity("");

        List<SpcyRsCity> list = spcyRsCityService.list();
        bean.setForder(list.size()+1);

        spcyRsCityService.save(bean);

        return HttpResult.ok("添加成功");
    }

    @ApiOperation(value = "城市-添加")
    @PostMapping(value = "addCity")
    public HttpResult addCity(@RequestBody SpcyRsCity bean){
        if (StringUtils.isBlank(bean.getProvinceid())){
            throw new BusinessException("省份参数！");
        }
        if (StringUtils.isBlank(bean.getCity())){
            throw new BusinessException("城市为空！");
        }
        bean.setId(GetUuIdUtils.ReplaceUuId());

        SpcyRsCity province = spcyRsCityService.getById(bean.getProvinceid());
        if (province == null){
            throw new BusinessException("省份不存在！");
        }
        province.setProvincecity(province.getProvince() + bean.getCity());

        bean.setProvince("");
        bean.setCityid("");
        bean.setArea("");

        List<SpcyRsCity> list = spcyRsCityService.list();
        bean.setForder(list.size()+1);

        spcyRsCityService.save(bean);

        return HttpResult.ok("添加成功");
    }

    @ApiOperation(value = "区域-添加")
    @PostMapping(value = "addArea")
    public HttpResult addArea(@RequestBody SpcyRsCity bean){
        if (StringUtils.isBlank(bean.getCityid())){
            throw new BusinessException("城市参数为空！");
        }
        if (StringUtils.isBlank(bean.getArea())){
            throw new BusinessException("区域为空！");
        }
        bean.setId(GetUuIdUtils.ReplaceUuId());

        SpcyRsCity city = spcyRsCityService.getById(bean.getCityid());
        if (city == null){
            throw new BusinessException("城市不存在！");
        }
        bean.setProvincecity(city.getProvincecity());
        bean.setProvincecityarea(city.getProvincecity() + bean.getArea());

        bean.setProvinceid("");
        bean.setProvince("");
        bean.setCity("");

        List<SpcyRsCity> list = spcyRsCityService.list();
        bean.setForder(list.size()+1);
        spcyRsCityService.save(bean);

        return HttpResult.ok("添加成功");
    }

    @ApiOperation(value = "省份城市-删除")
    @DeleteMapping(value = "delete")
    public HttpResult delete(String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("参数为空！");
        }

        SpcyRsCity bean = spcyRsCityService.getById(id);
        if (bean == null){
            throw new BusinessException("没有相匹配的数据！");
        }

        // 省份
        if (StringUtils.isBlank(bean.getProvinceid()) && StringUtils.isBlank(bean.getCityid())){
            List<SpcyRsCity> provinceList = spcyRsCityService.list(new LambdaQueryWrapper<SpcyRsCity>()
                    .eq(SpcyRsCity::getProvinceid, bean.getId()));
            if (CollectionUtil.isNotEmpty(provinceList)){
                throw new BusinessException("存在城市！无法删除！");
            }
        }

        // 城市
        if (StringUtils.isNotBlank(bean.getProvinceid())){
            List<SpcyRsCity> provinceList = spcyRsCityService.list(new LambdaQueryWrapper<SpcyRsCity>()
                    .eq(SpcyRsCity::getCityid, bean.getId()));
            if (CollectionUtil.isNotEmpty(provinceList)){
                throw new BusinessException("存在区县！无法删除！");
            }
        }

        spcyRsCityService.removeById(id);


        return HttpResult.ok("删除成功");
    }

}
